package com.hwh.blog.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.Response;

@ControllerAdvice
public class ControllerExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHandler(HttpServletRequest req , Exception e) throws Exception {
        logger.error("Request URL:{},Exception: {}",req.getRequestURI(),e);//记录异常
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class)!=null){
//            查找注解，如果不为空的话，将会跳转到指定的异常处理类，否则就跳转到自定义的错误页面
            throw e;
        }
        ModelAndView mv = new ModelAndView();
        mv.addObject("url",req.getRequestURI());
        mv.addObject("exception",e);
        mv.setViewName("error/error");

        return mv;
    }
}
